import 'dart:async';
import 'dart:io';

import 'package:star_author/event_bus/open_live_current_good_event.dart';
import 'package:star_author/event_bus/open_live_good_event.dart';
import 'package:star_author/utils/media_recorder_util.dart';
import 'package:star_author/utils/rouces_util.dart';
import 'package:star_author/widgets/dialog/dialog_type.dart';
import 'package:star_author/widgets/dialog/sure_dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../config/base_configuration.dart';
import '../../event_bus/global_event_bus.dart';
import '../../event_bus/open_live_current_event.dart';
import '../../generated/json/base/json_convert_content.dart';
import '../../utils/http/http_util.dart';
import 'model/live_good_list_entity.dart';

class openLiveCurrentGood extends StatefulWidget {
  bool isOpenLive;

  openLiveCurrentGood({Key? key, this.isOpenLive: false}) : super(key: key);

  @override
  State<openLiveCurrentGood> createState() => _openLiveCurrentGoodState();
}

class _openLiveCurrentGoodState extends State<openLiveCurrentGood> {
  int second = -1;

  late StreamSubscription<OpenLiveCurrentGoodEvent> _streamSubscriptionstream;

  late StreamSubscription<OpenLiveCurrentEvent>
      _streamSubscriptionstream2; //录播监听

  String getNumber(int number) {
    return number < 10 ? "0$number" : number.toString();
  }

  String getStr() {
    String result = "";
    int minute = second ~/ 60;
    if (minute >= 0) {
      result += getNumber(minute) + " : ";
    }
    int sec = second % 60;

    if (sec >= 0) {
      result += getNumber(sec);
    }
    return result;
  }

  List<LiveGoodListData> dataList = [];

  getCurrentGood(bool isInit) async {
    HttpUtil.commonRequest(
      Get.context!,
      '/api/v1/studios/${StreamConf.liveId}/backflows',
      isLoading: false,
      isErrorToast: false,
      queryParameters: {
        "explaining": true,
        "pre_page": 1,
      },
    ).then((value) async {
      LiveGoodListEntity? entity =
          JsonConvert.fromJsonAsT<LiveGoodListEntity>(value.data);
      dataList = entity?.data ?? [];
      if (dataList.length == 1 && isInit) {
        int id = dataList[0].id ?? 0;
        String filePath = await MediaRecorderUtil.getStoragePath();
        String path = filePath + "/" + id.toString() + ".mp4";
        File file = File(path);
        if (file.existsSync()) {
          //检测当前id在手机上面是否有文件 如果有文件 弹框给主播让他删除
          DialogUtil.showMyDialog(
            dialogType: DialogType.check_file_with_id,
            rightButtonOnTap: () {
              HttpUtil.commonRequest(
                Get.context!,
                '/api/v1/studios/${StreamConf.liveId}/stop_explaining',
                queryParameters: {
                  "backflow_id": id,
                },
                method: HttpUtil.MethodPut,
              ).then((value) {
                if (value.statusCode == 200) {
                  file.deleteSync();
                  String output_path =
                      filePath + "/" + id.toString() + "_c.mp4";
                  if (File(output_path).existsSync()) {
                    File(output_path).deleteSync();
                  }
                  MediaRecorderUtil.deleteLocalPage(id);
                  getCurrentGood(false);
                }
              });
            },
          );
        }
      }
      GlobalEventBus.instance.bus.fire(OpenLiveGoodEvent(dataList));
      updateState(() {});
    });
  }

  updateState(VoidCallback fn) {
    if (mounted) {
      setState(fn);
    }
  }

  initStream() {
    _streamSubscriptionstream = GlobalEventBus()
        .bus
        .on<OpenLiveCurrentGoodEvent>()
        .listen((event) async {
      if (event.liveGoodListData != null) {
        dataList = [event.liveGoodListData!];
      } else {
        dataList = [];
      }
      updateState(() {});
      GlobalEventBus.instance.bus.fire(OpenLiveGoodEvent(dataList));
    });
    second = 0;
    _streamSubscriptionstream2 =
        GlobalEventBus().bus.on<OpenLiveCurrentEvent>().listen((event) async {
      updateState(() {
        second = event.second;
        getStr();
      });
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Future.delayed(Duration(milliseconds: 500), () {
      getCurrentGood(true);
    });
    initStream();
  }

  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
    updateState(() {});
  }

  @override
  Widget build(BuildContext context) {
    if (!widget.isOpenLive) {
      return Container();
    }
    if (dataList.length == 0) {
      return Container();
    }
    if ((dataList[0].hasEvaluated ?? false)) {
      return Container();
    }
    if (MediaRecorderUtil.info == null) {
      return Container();
    }
    DecorationImage decorationImage = DecorationImage(
      scale: 2,
      image: const AssetImage('images/lt_common/temp_load.png'),
    );
    if ((dataList[0].goods?.cover?.url ?? "").isEmpty) {
      decorationImage = DecorationImage(
        scale: 2,
        image: const AssetImage('images/lt_common/temp_load.png'),
      );
    } else {
      decorationImage = DecorationImage(
          image: NetworkImage(dataList[0].goods?.cover?.url ?? ""),
          fit: BoxFit.cover);
    }

    return Positioned(
      child: GestureDetector(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              width: 48.w,
              height: 18.w,
              alignment: Alignment.center,
              child: Image(
                image: AssetImage(
                    'images/lt_user/owner/level_${dataList[0].user_normal_level}.png'),
                width: 26.w,
                height: 14.w,
                fit: BoxFit.cover,
              ),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(4.w),
                  topRight: Radius.circular(4.w),
                ),
              ),
            ),
            Stack(
              children: [
                Container(
                  width: 48.w,
                  height: 48.w,
                  decoration: BoxDecoration(
                    image: decorationImage,
                  ),
                ),
                Positioned(
                  child: Container(
                    width: 48.w,
                    color: Color(0x4D000000),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Image.asset(
                          'images/video_loading_lt.gif',
                          width: 7.w,
                          height: 7.w,
                        ),
                        SizedBox(
                          width: 3.w,
                        ),
                        Text(
                          '讲解中',
                          style: TextStyle(
                            fontSize: 8.sp,
                            color: Colors.white,
                          ),
                        )
                      ],
                    ),
                  ),
                  bottom: 0,
                )
              ],
            ),
            Container(
              width: 48.w,
              height: 23.w,
              alignment: Alignment.center,
              child: Stack(
                children: [
                  Image.asset(
                    RoucesUtil.getAssets('ic_current_bidder_msg_lt'),
                    width: 48.w,
                    height: 23.w,
                    fit: BoxFit.cover,
                  ),
                  Container(
                    alignment: Alignment.center,
                    margin: EdgeInsets.only(bottom: 3.w),
                    child: Text(
                      "${MediaRecorderUtil.info == null ? "00:00:00" : getStr()}",
                      style: TextStyle(
                          fontSize: 12.sp,
                          fontWeight: FontWeight.w500,
                          color: Colors.white),
                    ),
                  )
                ],
              ),
            ),
          ],
        ),
        onTap: () {},
      ),
      bottom: MediaQuery.of(context).padding.bottom + 7.w + 40.w + 12.w + 5.w,
      right: 8.w,
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _streamSubscriptionstream.cancel();
    _streamSubscriptionstream2.cancel();
  }
}
